package com.yh.csx.bsf.flow.engine.state;

import com.yh.csx.bsf.core.thread.ThreadPool;
import com.yh.csx.bsf.flow.provider.enums.FlowLogEnum;
import com.yh.csx.bsf.flow.core.db.DbHelper;
import com.yh.csx.bsf.flow.dao.dal.t_flow_dal;
import com.yh.csx.bsf.flow.dao.dal.t_flow_log_dal;
import com.yh.csx.bsf.flow.dao.dal.t_task_dal;
import com.yh.csx.bsf.flow.dao.model.auto.t_flow_log_model;
import com.yh.csx.bsf.flow.dao.model.auto.t_flow_model;
import com.yh.csx.bsf.flow.dao.model.auto.t_task_model;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import lombok.var;

import java.util.Date;

/**
 * @author: chejiangyi
 * @version: 2019-10-30 15:13
 **/
@Slf4j
public class BaseFlow {
    protected t_task_model getTaskModel(int taskid){
        return DbHelper.get((c)->new t_task_dal().get(c,taskid));
    }
    
    protected t_flow_model getFlowModel(int flowid){
       return  DbHelper.get((c)-> new t_flow_dal().get(c,flowid));        
    }

    protected String getFlowTitle(int flowid){
       return DbHelper.get((c)-> new t_flow_dal().getTitle(c,flowid));        
    }
    
    protected void logFlowLog(int flowid,String message){
        String flowTitle = "";
        try{flowTitle = getFlowTitle(flowid);}catch (Exception ex){}
        val model = new t_flow_log_model(0, (byte) FlowLogEnum.common.Value,message,flowid,flowTitle,new Date());
        DbHelper.noTransactionCall((c)-> new t_flow_log_dal().add(c,model));
        log.info("流程flowid:"+flowid+" 流转日志:"+message);
    }

    protected void logFlowDebug(int flowid,String message){
        String flowTitle = "";
        try{flowTitle = getFlowTitle(flowid);}catch (Exception ex){}
        val model = new t_flow_log_model(0, (byte)FlowLogEnum.debug.Value,message,flowid,flowTitle,new Date());
        DbHelper.noTransactionCall((c)-> new t_flow_log_dal().add(c,model));
        log.debug("流程flowid:"+flowid+" 流转debug日志:"+message);
    }

    protected void logFlowError(int flowid,Exception e){
        if(e instanceof StateEngineException)
        {
            /// todo list 此处在设计上面未来要考虑优化 主要解决同个事务下死锁等待的问题
            ThreadPool.System.submit("异步同步错误信息,",()->
                {
                    DbHelper.noTransactionCall((c)-> new t_flow_dal().updateFlowError(c,flowid,e.getMessage()));
                }
            );
        }
        onlyLogError(flowid,e);
    }

    protected void onlyLogError(int flowid,Exception e){
        var flow_error = e.getMessage();
        if(e instanceof StateEngineException){
            flow_error = ((StateEngineException)e).getDetailMessage();
        }
        String flowTitle = "";
        try{flowTitle = getFlowTitle(flowid);}catch (Exception ex){}
        val model = new t_flow_log_model(0, (byte)FlowLogEnum.error.Value,flow_error,flowid,flowTitle,new Date());
        DbHelper.noTransactionCall((c)-> new t_flow_log_dal().add(c,model));
        log.error("流程flowid:"+flowid+" 流转出错",e);
    }

}
